import React, { useMemo } from "react";
import { useRem } from "../utils/global";
import "./wrap.less";

const classPrefix = `bbt-react-wrap`;

export type WrapProps = {
  children: React.ReactNode;
  styles?: React.CSSProperties;
  /** 自定义类名 */
  className?: string;
  /** 行数 */
  rows?: number;
  /** 行高 */
  lineHeight: number;
  /** 列间距 */
  spacing?: number;
  /** 行间距 */
  runSpacing?: number;
  /** px转换rem方法 */
  px2rem?: (px: number) => string;
};

export const Wrap = (props: WrapProps) => {
  const {
    children,
    styles,
    className = "",
    rows = 0,
    lineHeight = 30,
    spacing = 0,
    runSpacing = 0,
    px2rem,
  } = props;

  const usePx2rem = useRem(px2rem);

  const content = useMemo(() => {
    if (Array.isArray(children)) {
      return children?.map((child, index) => {
        return (
          <div
            key={index}
            className={`${classPrefix}-item`}
            style={{
              height: usePx2rem(lineHeight),
              marginBottom: usePx2rem(runSpacing),
              marginRight: usePx2rem(spacing),
            }}
          >
            {child}
          </div>
        );
      });
    } else {
      return children;
    }
  }, [children, lineHeight, runSpacing, spacing]);

  const maxHeight = useMemo(() => {
    if (rows == 0) return null;
    return usePx2rem(rows * (lineHeight + runSpacing));
  }, [rows, lineHeight, runSpacing]);

  return (
    <div
      className={`${classPrefix} ${className}`}
      style={{
        maxHeight,
        ...styles,
        marginBottom:
          runSpacing > 0 ? `-${usePx2rem(runSpacing)}` : usePx2rem(runSpacing),
      }}
    >
      {content}
    </div>
  );
};
